var layer = require('layer');
var request = require('request');
var func = require('{pub}/function');
var base64 = require('{polyfill}/base64');
// var mob = require('mobile');
// mob()
return function(){
    var that = this;
    var mobileOld = '';//已经验证的手机号码(不做重复请求)
    var mobileOldmsg = '';//已经验证的手机号码的结果
    var vali = {//验证
        mobile:{
            selector:'name',//选择器
            mode:'regular',//验证方式 plain表示普通（非空），regular表示正则
            regular:/^1[34578]\d{9}$/
        },
        password:{
            selector:'name',
            mode:'regular',
            regular:/^([a-z0-9\.\@\!\#\$\%\^\&\*\(\)]){6,20}$/i
        },
        twopassword:{
            selector:'name',
            mode:'plain'
        },
        name:{
            selector:'name',
            mode:'plain'
        },
        carea:{
            selector:'name',
            mode:'plain'
        },
        cord:{
            selector:'name',
            mode:'plain'
        },
    };
    
    
    $('body').on('mouseover','.ui-site',function(){//鼠标经过显示选择地址
        var _this = $(this);
        _this.addClass('s-show');
    }).on('mouseout','.ui-site',function(){//鼠标离开关闭选择地址
        var _this = $(this);
        _this.removeClass('s-show');
        
    }).on('click', '.ui-site-tab .item span a', function(){//点击选择地址
		var me = $(this);
		var item = me.parent();
		var tab = $('.ui-site-tab');
		var index = tab.find('.ui-tab li.s-crt').index();
		var site = tab.closest('.ui-site');
        item.addClass('s-crt').siblings().removeClass('s-crt');
        $('.ui-site-title').removeClass('s-err');
        $('.ui-tab li.s-crt a').html(me.text());
        if(index < 2){
            tab.find('.ui-tab li').eq(index).nextAll().remove();
            tab.find('.ui-tabody .item').eq(index).nextAll().remove();
            site.addClass('s-shows');
            var text = '城市';
            var addid = 'citysel';
            if(index == 1){
                text = '区县';
                addid = 'carea';
            }
            var html = '<li class="s-crt"><a href="javascript:void(0);" target="_self">'+ text +'</a></li>';
            var html1 = '<div areaid="'+ me.attr('areaid') +'" class="item f-clearfix"></div>';
            $('.ui-tab li').removeClass('s-crt');
            $('.ui-tab').append(html);
            $('.ui-tabody').append(html1);
            $('.ui-form [name=carea]').parents('.ui-item').children('.f-cred').removeClass('ingreen').html('*');
            add(addid,me);
        }else{
            $('.ui-form [name=carea]').parents('.ui-item').children('.f-cred').addClass('ingreen').html('&#xe651;');
            site.removeClass('s-shows s-show'); 
        }
		var text = [];
		var name = ['provsel', 'citysel', 'carea'];
		if($('#addAreald').length == 1){
			name = ['provsel', 'citysel', 'areald'];
		}
		tab.find('.item span.s-crt').each(function(key, val){
			var crt = $(this).children('a');
			text.push(crt.text());
			$('[name="'+ name[key] +'"]').val(crt.attr('areaid')).next('input:hidden').val('')
		});
        site.parent().find('.ui-err').empty()
		site.find('.ui-site-title b').addClass('color32').html(text.join('-'));
    }).on('click','.ui-tab li',function(){//点击重新选择
        var _this = $(this),
            index = _this.index();
        _this.addClass('s-crt').siblings('li').removeClass('s-crt');
        $('.ui-tabody .item').eq(index).show().siblings('.item').hide();

    }).on('click','.g_pop_clear',function(){//关闭地址弹出层
        $('.ui-site-tab').parents('.ui-site').removeClass('s-shows s-show'); 
    }).on('blur','.ui-form .ui-input',function(){//失去焦点验证
        var _this = $(this),
            inname = _this.attr('name');
        if(_this.hasClass('ui-site-title')){
            return false;
        }
        validate(inname);
    }).on('focus','.ui-form .ui-input',function(){//获得焦点去除错误信息
        var _this = $(this);
        _this.removeClass('s-err').parents('.ui-item').find('.ui-err').children('label').hide();
        if(_this.attr('name') == 'password'){
            if(!_this.parents('.ui-item').find('.eye').hasClass('eyeshow')){
                if(!_this.hasClass('onie8')){
                    _this.attr('type','password');
                }
            }
        }
    }).on('click','.ui-form .ui-button',function(){//注册按钮点击
        var inname = '',
            x = 0,
            y = 0;
        for(var i in vali){
            inname = i;
            x++;
            if(validate(inname)){
                y++;
            }
        }
        if(x == y){
            var mobile = $('.ui-form [name=mobile]').val().replace(/\s/g, ""),
                password = base64.encode($('.ui-form [name=password]').val()),
                rePassword = base64.encode($('.ui-form [name=twopassword]').val()),
                realName = $('.ui-form [name=name]').val(),
                areaCode = $('.ui-form [name=carea]').val(),
                verifyCode = $('.ui-form [name=cord]').val();
            request.post('/user/register', {
                mobile:mobile,
                password:password,
                rePassword:rePassword,
                realName:realName,
                areaCode:areaCode,
                verifyCode:verifyCode
            }, {
                200:function(res){
                    func.location('list');
                },
                other:function(res){
                    if(res.message =='验证码错误'){
                        $('.ui-form [name=cord]').val('').focus();
                    }else{
                        
                    }
                }
            }, '正在注册...')
        }
    }).on('keyup change','.ui-form .ui-input',function(e){//监听 是否显示清空按钮和显示密码//keydown去除了
        var _this = $(this),
            _len = _this.val().length;
        if(_len > 0){
            _this.parents('.ui-item').find('.inpclear').removeClass('none');
            if(_this.attr('name') == 'password' || _this.attr('name') == 'twopassword'){
                _this.parents('.ui-item').find('.eye').removeClass('none');
                if(_this.attr('name') == 'password'){
                    if(_len >= 6){
                        $('[name="twopassword"]').removeAttr('disabled');
                    }else{
                        $('[name="twopassword"]').attr('disabled','disabled');
                    }
                    
                }
            }else if(_this.attr('name') == 'mobile'){//&& e.keyCode != '37' && e.keyCode != '38' && e.keyCode != '39' && e.keyCode != '40'

                var _this = $(this);
                var _val = _this.val().replace(/\s/g, ""),
                    _lens = _val.length,
                    _nueval = '';
                if(_lens <= 3){
                    _nueval = _val;
                }
                if(_lens > 3){
                    _nueval = _val.substring(0,3) + ' ' + _val.substring(3);
                }
                if(_lens > 7){
                    _nueval = _val.substring(0,3) + ' ' + _val.substring(3,7) + ' ' + _val.substring(7);
                }
                if(_lens >= 11){//手机号码获取去验证是否注册
                    _nueval = _val.substring(0,3) + ' ' + _val.substring(3,7) + ' ' + _val.substring(7,11);
                }
                _this.val(_nueval);
                // $('.ui-form [name=mobile]').mobile({
                //     e:e
                // });
            }
        }else{
            _this.parents('.ui-item').find('.inpclear').addClass('none');
            if(_this.attr('name') == 'password' || _this.attr('name') == 'twopassword'){
                _this.parents('.ui-item').find('.eye').addClass('none');
                if(_this.attr('name') == 'password'){
                    $('[name="twopassword"]').attr('disabled','disabled');
                }
           }
        }
    }).on('click','.ui-form .inpclear',function(){//清空文本框
        var _this = $(this);
        _this.addClass('none').parents('.ui-item').find('.ui-input').val('');
        if(_this.parents('.ui-item').find('.ui-input').attr('name') == 'password' || _this.parents('.ui-item').find('.ui-input').attr('name') == 'twopassword'){
            _this.siblings('.eye').addClass('none');
            if(_this.parents('.ui-item').find('.ui-input').attr('name') == 'password'){
                $('[name="twopassword"]').attr('disabled','disabled');
            }
        }
    }).on('click','.ui-form .eye',function(){//密码显示文本
        var _this = $(this);
        if(_this.hasClass('eyeshow')){
            _this.removeClass('eyeshow').html('&#xe659;');
            if(_this.parents('.ui-item').find('.ui-input').hasClass('onie8')){
                var _html = _this.siblings('strong').html().replace('type=text','type=password');
                _this.siblings('strong').html(_html);
            }else{
                _this.parents('.ui-item').find('.ui-input').attr('type','password');
            }
            
        }else{
            _this.addClass('eyeshow').html('&#xe65a;');
            if(_this.parents('.ui-item').find('.ui-input').hasClass('onie8')){
                var _html = _this.siblings('strong').html().replace('type=password','type=text').replace('value="','value="'+_this.parents('.ui-item').find('.ui-input').val());
                _this.siblings('strong').html(_html);
            }else{
                _this.parents('.ui-item').find('.ui-input').attr('type','text');
            }
        }
    }).on('click','.oncord',function(){//获取验证码
        var _this = $(this);
        if(!_this.hasClass('timefag')){
            gaincord();
        }
    })

    var mobilefig = false;
    function gaincord(){//获取验证码
        if(mobilefig){
            request.get('/user/getVerifyCode', {
                'mobile':$('.ui-form [name=mobile]').val().replace(/\s/g, "")
            }, {
                200:function(res){
                    gotime();
                },
                other:function(res){
                    // layer({
                    //     content:'<p style="padding:20px; height:auto;">'+res.message+'</p>',
                    //     scrollbar:false,
                    //     padding:20,
                    //     width:300,
                    //     title:'提示',
                    //     cancel:{
                    //         enable:true,
                    //         text:'关闭'
                    //     }
                    // });
                }
            }, '正在获取验证码...')
        }else{
            $('.ui-form [name=mobile]').focus().blur();
        }
    }
    function gotime(){//倒计时
        var time = 60;
        $('.oncord').html(time+'s');
        $('.oncord').addClass('timefag');
        var auto = setInterval(function(){
            time--;
            $('.oncord').html(time+'s');
            if(time == 0){
                $('.oncord').html('再次获取');
                clearInterval(auto);
                $('.oncord').removeClass('timefag');
            }
        },1000)
    }

    function validate(inname){//验证
        var fig = false;
        if(vali[inname].selector == 'name'){
            var _val = $('.ui-form [name='+inname+']').val();
            if(inname == 'mobile'){
                _val = _val.replace(/\s/g, "")
            }
            if(vali[inname].mode == 'plain'){
                _val.length > 0?fig = true:fig = false;
            }else{
                vali[inname].regular.test(_val)?fig = true:fig = false;
            }
            if(inname == 'twopassword'){
                _val == $('.ui-form [name=password]').val() && _val?fig = true:fig = false;
            }
        }
        if(!fig){
            if(inname == 'mobile'){
                mobilefig = false;
            }
            if(inname == 'carea'){
                $('.ui-site-title').addClass('s-err');
            }else{
                $('.ui-form [name='+inname+']').addClass('s-err');
            }
            $('.ui-form [name='+inname+']').parents('.ui-item').find('.ui-err').html('<label for="mobile" class="s-err" style="display: block;">'+$('.ui-form [name='+inname+']').attr('data-msg-required')+'</label>').parents('.ui-item').children('.f-cred').removeClass('ingreen').html('*');
        }else{
            if(inname == 'mobile'){//验证手机号码是否已经注册
                var _val = $('.ui-form [name='+inname+']').val().replace(/\s/g, "");
                if(_val == mobileOld){
                    mobilefig = !mobileOldmsg;
                }else{
                    request.get('/user/verifyMobile', {
                        'mobile':$('.ui-form [name='+inname+']').val().replace(/\s/g, "")
                    }, {
                        200:function(res){
                            mobileOld=_val;
                            mobileOldmsg = res.data.result;
                            if(res.data.result == false){
                                $('.ui-form [name='+inname+']').parents('.ui-item').children('.f-cred').addClass('ingreen').html('&#xe651;');
                                mobilefig = true;
                            }else{
                                mobilefig = false;
                                layer({
                                    content:'<p style="padding:20px; height:auto;">您的手机号码已经存在，请直接登录</p>',
                                    scrollbar:false,
                                    padding:20,
                                    width:300,
                                    title:'提示',
                                    cancel:{
                                        enable:true,
                                        text:'关闭'
                                    }
                                });
                            }
                        },
                        other:function(res){
                           
                        }
                    }, '正在验证...')
                }
            }else{
                $('.ui-form [name='+inname+']').parents('.ui-item').children('.f-cred').addClass('ingreen').html('&#xe651;');
            }
        }
        return fig;
    }

    function add(addid,me){//获取地址信息
        var url = 'areaInfo/getProvinceList';
        var item = $('.ui-tabody .item').eq(0);
        var areaInfo = {};
        if(addid === 'citysel'){//城市
            url = 'areaInfo/getCityList';
            item = $('.ui-tabody .item').eq(1);
            
            areaInfo={
                provinceId:me.attr('areaid')
            }
        }else if(addid === 'carea'){//区
            url = 'areaInfo/getCountyList';
            item = $('.ui-tabody .item').eq(2);
            areaInfo={
                cityId:me.attr('areaid')
            }
        }
        request.get(url,areaInfo,{
            200:function(res){
                var red = '';
                if(addid === 'citysel'){//城市
                    red = res.data.cityList;
                }else if(addid === 'carea'){//区
                    red = res.data.countyList;
                }else{
                    red = res.data.provinceList;
                }
                if(red.length){
                    var html = (function(list){
                        var arr = [];
                        $.each(list, function(key, val){
                            arr.push('<span><a href="javascript:void(0);" areaid="'+ val.areaId +'" title="'+ val.areaName +'">'+ val.areaName +'</a></span>');
                        });
                        return arr.join('');
                    })(red);
                    item.html(html);
                }
                else{
                    item.html('<span>暂无数据</span>');
                }
                item.siblings('div').hide();
            },
            other:function(res){
                item.html('<span>暂无数据</span>');
            }
        },null)
    }add('provsel');
}